package com.example.yu.perfect_demo;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;

import com.example.yu.perfect_demo.fragment.FoundFragment;
import com.example.yu.perfect_demo.fragment.HomeFragment;
import com.example.yu.perfect_demo.fragment.ListenerMeFragment;
import com.example.yu.perfect_demo.fragment.UserFragment;


import butterknife.BindView;
import butterknife.ButterKnife;

public class HomeActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {

    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.tab)
    TabLayout tab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        initView();
        showFragment(0);
    }

    private void initView() {
        initTabLayout();
    }

    private void initTabLayout() {
        tab.addTab(tab.newTab().setText("首页").setTag(0));
        tab.addTab(tab.newTab().setText("我听").setTag(1));
        tab.addTab(tab.newTab().setText("发现").setTag(2));
        tab.addTab(tab.newTab().setText("未登录").setTag(3));
        tab.addOnTabSelectedListener(this);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int index = (int) tab.getTag();
        showFragment(index);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }


    private Fragment[] fragments = new Fragment[4];


    private int currentIndex = -1;

    private void showFragment(int nextIndex) {
        if (nextIndex == currentIndex)
            return;
        FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
        if (fragments[nextIndex] == null) {
            switch (nextIndex) {
                case 0:
                    fragments[nextIndex] = new HomeFragment();
                    break;
                case 1:
                    fragments[nextIndex] = new ListenerMeFragment();
                    break;
                case 2:
                    fragments[nextIndex] = new FoundFragment();
                    break;
                case 3:
                    fragments[nextIndex] = new UserFragment();
                    break;
            }

            bt.add(R.id.fl_container, fragments[nextIndex]);
        } else {
            bt.show(fragments[nextIndex]);
        }
        if (currentIndex != -1)
            bt.hide(fragments[currentIndex]);
        bt.commit();
        currentIndex = nextIndex;
    }


}
